package sort;

import java.io.*;
import java.nio.*;
import java.nio.channels.*;

import java.nio.ByteBuffer;

/**
 *
 * @author BDSHADOW
 */
public class BigReadWrite {
    private int size = 0;
    public int[] readArray(String from) {
         MappedByteBuffer reader = null;
         FileChannel channel = null;
         int numbers[] = null;
         int[] array = null;
         int k = 0;
         
         try {
         channel = new RandomAccessFile(from, "r").getChannel();
         size = (int)channel.size(); 
         reader = channel.map(FileChannel.MapMode.READ_ONLY, 0, size);
         channel.close();
         
         int length = 0;
         while (reader.hasRemaining()) {
             if (reader.get() == ' ') length++;
         }
         reader.position(0);
         array = new int[length + 1];

         StringBuilder sb = new StringBuilder();
         while (reader.hasRemaining()) {
             sb.delete(0, sb.length());
             byte symb = reader.get();
             while ((symb != ' ') && reader.hasRemaining()) {
                 sb.append((char)symb);
                 symb = reader.get();
             }
             if (!reader.hasRemaining()) {
                 sb.append((char)symb);
             }
             array[k++] = Integer.valueOf(sb.toString()).intValue();
         }
         } catch (FileNotFoundException e) {
             System.out.println("File wasn't found");
         } catch (IOException e) {
             System.out.println("File can't be read");
         }
           
         //int[] arr = new int[k];
         //System.arraycopy(array, 0, arr, 0, k);
         return array;
     }
     
     public void writeArray(int[] arr, String src) {
         MappedByteBuffer writer = null;
         FileChannel channel = null;
         
         try {
         channel = new RandomAccessFile(src, "rw").getChannel();
         writer = channel.map(FileChannel.MapMode.READ_WRITE, 0, size + 1);
         channel.close();
         
         writer.position(0);
         for (int i = 0; i < arr.length; i++) {
             int digits = String.valueOf(arr[i]).length();             
             ByteBuffer num = ByteBuffer.allocate(digits + 1);
             num.put((String.valueOf(arr[i] + " ").getBytes()));
             num.position(0);             
             writer.put(num);
         }
         writer.force();
         
         } catch (FileNotFoundException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         }
     }
}
